<?php
/**
 * Created by PhpStorm.
 * User: zhengzifan
 * Date: 2017/3/16
 * Time: 11:05
 */

namespace app\admin\controller;
use think\Loader;

class ContractController extends CommonController{

    public $model;
    public $states;
    public $levels;
    public $industries;
    public $businesses_id;
    
    public $TableColumnNameArr = [
        '合同编号' => 'contract_no',
        '合同类型' => 'mode_id',
        '租赁类型' => 'hire_mode',
        '所属业务' => 'service_id',
        '所属客户' => 'customer_id',
        '所属门店' => 'store_id',
        '选择车辆' => 'car_id',
        '联系人' => 'contactor_name',
        '开始日期' => 'start_time',
        '到期日期' => 'end_time',
        '合同资料' => 'cert_files',
        '说明' => 'remark'
    ];

    /**
     * 初始化adminModel
     */
    public function _initialize(){
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = model('Contract');
        $this->businesses_id = 0;
        if(!empty(session('admin')['businesses_id']) && session('admin')['businesses_id'] > 0){
            $this->businesses_id = session('admin')['businesses_id'];
        }
        $businesses = db('businesses')->select();
        $this->assign([
            'businesses_id' => $this->businesses_id,
            'businesses' => $businesses
        ]);
    }

    /**
     * 列表页
     */
    public function index(){
        $keyword = input('param.keyword');
        $customer_id = input('param.customer_id');
        $car_id = input('param.car_id');
        $mode_id = input('param.mode_id');
        $store_id = input('param.store_id');
        $service_id = input('param.service_id');
        $where['a.id']=['>',0];
        $stores = db('Store')->where(['id'=>['>','0']])->select();
        $store_ids = model('AdminStore')->where(['admin_id'=>session('admin')['id']])->column('store_id');
        if(!empty($store_ids) && count($store_ids)>0){
            $where['a.store_id'] = ['in',$store_ids];
            $stores = db('Store')->where(['id'=>['in',$store_ids]])->select();
        }
        if($customer_id && $customer_id>0){
            $where['a.customer_id'] = $customer_id;
        }
        if($car_id && $car_id>0){
            $where['a.car_id'] = $car_id;
        }
        if($mode_id && $mode_id>0){
            $where['a.mode_id'] = $mode_id;
        }
        if($store_id && $store_id>0){
            $where['a.store_id'] = $store_id;
        }
        if($service_id && $service_id>0){
            $where['a.service_id'] = $service_id;
        }
        if($keyword){
            $where['a.contract_no|a.contactor_name|a.remark|service_name|mode_text|customer_name|plate_no|car_name|store_name'] = ['like','%'.$keyword.'%'];
        }
        if($this->businesses_id > 0){
            $where['a.businesses_id'] = $this->businesses_id;
        }
        $customers = db('Customer')->where(['id'=>['>','0']])->select();
        $carlist = db('Cars')->where(['id'=>['>','0']])->select();
        $modes = db('CommonEnum')->where(['mode_name'=>'合同类型'])->select();
        $services = db('CommonEnum')->where(['mode_name'=>'业务'])->select();
        $list = $this->model->where($where)
        ->alias('a')
        ->join('__COMMON_ENUM__ cm',"cm.id=a.mode_id and cm.mode_name='合同类型'",'LEFT')
        ->join('__COMMON_ENUM__ ss',"ss.id=a.service_id and ss.mode_name='业务'",'LEFT')
        ->join('__CUSTOMER__ cu',"cu.id=a.customer_id",'LEFT')
        ->join('__CARS__ cc',"cc.id=a.car_id",'LEFT')
        ->join('__STORE__ st',"st.id=a.store_id",'LEFT')
        ->field('a.*,ss.name as service_name,cm.name as mode_text,cu.real_name as customer_name,cc.plate_no as plate_no,cc.name as car_name,st.name as store_name')
        ->paginate(20,false,['query' => request()->param()]);
		$page = $list->render();
        $this->assign([
            'list'=>$list,
            'page'=>$page,
            'keyword'=>$keyword,
            'customer_id'=>$customer_id,
            'car_id'=>$car_id,
            'mode_id'=>$mode_id,
            'store_id'=>$store_id,
            'service_id'=>$service_id,
            'customers'=>$customers,
            'carlist'=>$carlist,
            'modes'=>$modes,
            'stores'=>$stores,
            'services'=>$services
        ]);
        return $this->fetch('index');
    }

    /**
     * 新增与修改
     */
    public function info(){
        $post_id = input('param.id');
        $get_id = input('param.id');
        $info = $this->model->where(['id'=>$get_id])->find();
        $customers = db('Customer')->where(['id'=>['>','0']])->select();
        $modes = db('CommonEnum')->where(['mode_name'=>'合同类型'])->select();
        $stores = db('Store')->where(['id'=>['>','0']])->select();
        $services = db('CommonEnum')->where(['mode_name'=>'业务'])->select();
        $hire_modes=db('CarConfig')->where(['config_mode'=>2])->select();
        $start_time = time();
        $end_time = time();
        $img_ext_list =  ['jpg', 'png', 'gif', 'jpeg'];
        $date = date('YmdHis',time());
        $longtime = (microtime(true)-time())*10000;
        settype($longtime, "integer"); 
        $contract_no = 'hrc'.$date.str_pad($longtime, 4, "0", STR_PAD_LEFT);
        $contract_id = 0;
        $order_car_id = 0;
        if($info){
            $start_time = $info['start_time'];
            $end_time = $info['end_time'];
            $contract_no = $info['contract_no'];
            $contract_id = $info['id'];
            $order_car_id = $info['order_car_id']?$info['order_car_id']:0;
        }
        $contractFileArr = array();
        $contractFileList = db('ContractFile')->where(['contract_id'=>$contract_id])->select();
        foreach($contractFileList as $item){
            $contractFileArr[] = $item['file_url'];
        }
        $contractCarArr = array();
        $contractCarList = db('ContractCar')->where(['contract_id'=>$contract_id])->select();
        foreach($contractCarList as $item){
            $contractCarArr[] = $item['car_id'];
        }
        if(IS_POST){
            $data = input('param.');
            $data['create_time'] = strtotime($data['create_time']);
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['order_car_id'] = $order_car_id;
            $data['car_id'] = 0;
            $car_ids = $data['car_ids'];
            $contract_files = $data['contract_files'];
            $data['data_count'] = count($contract_files);
            unset($data['car_ids']);
            unset($data['contract_files']);
            $ip = $this->request->ip();
            if($post_id && $post_id>0){
			    $data['updator_id'] = session('admin')['id'];
                $data['update_time'] = time();
                if($this->model->isUpdate(true)->save($data)){
                    //保存车辆信息
                    $this->saveContractCar($contract_id,$order_car_id,$car_ids,$contractCarArr);
                    //保存合同资料
                    $this->saveContractFile($contract_id,$contract_files,$contractFileArr);
                    admin_log("编辑合同信息，ID：$post_id");
					$this->redirect('Contract/index');
                }else{
                    $this->error($this->model->getError());
                }
            }else{
                //新增操作
			    $data['creator_id'] = session('admin')['id'];
                $data['create_time'] = time();
			    $data['updator_id'] = session('admin')['id'];
                $data['update_time'] = time();
                if($this->model->save($data)){
                    $contract_id = $this->model->id;
                    //保存车辆信息
                    $this->saveContractCar($contract_id,$order_car_id,$car_ids,$contractCarArr);
                    //保存合同资料
                    $this->saveContractFile($contract_id,$contract_files,$contractFileArr);
                    admin_log("新增合同信息，ID：".$contract_id);
				    $this->redirect('Contract/index');
                }else{
                    $this->error($this->model->getError());
                }
            }
        }
        $this->assign([
            'info' => $info,
            'customers'=>$customers,
            'carlist'=>$contractCarArr,
            'contract_id'=>$contract_id,
            'modes'=>$modes,
            'stores'=>$stores,
            'services'=>$services,
            'hire_modes'=>$hire_modes,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'contract_no'=>$contract_no,
            'contract_file_list'=>$contractFileList,
            'img_ext_list'=>$img_ext_list
        ]);
        return $this->fetch('info');
    }

    /**
     * 保存合同资料
     */
    protected function saveContractFile($contract_id,$contract_files,$contractFileArr){
        $ip = $this->request->ip();
        $contractFileInsert = array();
        
        //新增资料
        foreach($contract_files as $item){
            if(count($contractFileArr)<=0 || !in_array($item,$contractFileArr)){
                if($item){
                    $file_ext = '';
                    $file_arr = explode('.',$item);
                    if(count($file_arr)>1){
                        $file_ext = $file_arr[count($file_arr)-1];
                    }
                    $contractFileInsert[] = [
                        'file_name' => $item,
                        'file_url' => $item,
                        'contract_id' => $contract_id,
                        'creator_id' => session('admin')['id'],
                        'create_time' => time(),
                        'file_ext' => $file_ext,
                        'ip' => $ip
                    ];
                }
            }
        }
        if(!empty($contractFileInsert) && count($contractFileInsert)>0){
            model('ContractFile')->saveAll($contractFileInsert);
        }
        if($contractFileArr && count($contractFileArr)>0){
            //删除资料
            foreach($contractFileArr as $item){
                if(!in_array($item,$contract_files)){
                    model('ContractFile')->where(['contract_id'=>$contract_id,'file_url'=>$item])->delete();
                }
            }
        }
    }

    /**
     * 保存车辆信息
     */
    protected function saveContractCar($contract_id,$order_car_id,$car_ids,$contractCarArr){
        $ip = $this->request->ip();
        $contractCarInsert = array();
        
        //新增车辆
        foreach($car_ids as $item){
            if(count($contractCarArr)<=0 || !in_array($item,$contractCarArr)){
                $contractCarInsert[] = [
                    'car_id' => $item,
                    'contract_id' => $contract_id,
                    'order_id' => $order_car_id
                ];
            }
        }
        if(!empty($contractCarInsert) && count($contractCarInsert)>0){
            model('ContractCar')->saveAll($contractCarInsert);
        }
        //删除车辆
        if($contractCarArr && count($contractCarArr)>0){
            foreach($contractCarArr as $item){
                if(!in_array($item,$car_ids)){
                    model('ContractCar')->where(['contract_id'=>$contract_id,'car_id'=>$item])->delete();
                }
            }
        }
    }

    /**
     * 删除
     */
    public function del(){
        $get_id = input('param.id');
        if($this->model->where(['id'=>$get_id])->delete()){
            db('ContractCar')->where(['contract_id'=>$get_id])->delete();
            db('ContractCert')->where(['contract_id'=>$get_id])->delete();
            admin_log("删除合同信息，ID：$get_id");
            $this->redirect('Contract/index');
        }else{
            getAlert('操作失败！');
        }
    }
    
    /**
     * 获取车辆信息
     */
    public function ajax_car_list(){
        $store_id = input('param.store_id');
        $contract_id = input('param.contract_id');
        $where['id'] = ['>','0'];
        if($store_id){
            $where['store_id'] = $store_id;
        }
        $contractCarArr = array();
        $contractCarList = db('ContractCar')->where(['contract_id'=>$contract_id])->select();
        foreach($contractCarList as $item){
            $contractCarArr[] = $item['car_id'];
        }
        $list = db('Cars')->where($where)->select();

        $this->assign([
            'list' => $list,
            'contractCarArr'=>$contractCarArr
        ]);
        return $this->fetch('ajax_car_list');
    }
    
    /*
     * 导入Excel
    */
    public function import_data(){
        $json = [
            'status' => 0,
            'msg' => '请选择导入数据文件'
        ];
        $file_urls = input('file_url');
        if(!empty($file_urls) && count($file_urls)>0){
            Loader::import('PHPExcel.PHPExcel');
            Loader::import('PHPExcel.PHPExcel.PHPExcel_IOFactory');
            Loader::import('PHPExcel.PHPExcel.PHPExcel_Cell');
            //实例化PHPExcel
            $objPHPExcel = new \PHPExcel();
            $stModel = model('store');
            $ctModel = model('Customer');
            $ceModel = model('CommonEnum');
            $customers = $ctModel->where(['id'=>['>','0']])->select();
            $modes = $ceModel->where(['mode_name'=>'合同类型'])->select();
            $stores = $stModel->where(['id'=>['>','0']])->select();
            $services = $ceModel->where(['mode_name'=>'业务'])->select();
            $hire_modes = db('CarConfig')->where(['config_mode'=>2])->select();
            $cars=db('Cars')->where(['id'=>['>',0]])->select();
            foreach($file_urls as $path){
                $path = ROOT_PATH.$path;
                $re = actionRead($path, 'utf-8');
                $imgs = extractImageFromWorksheet($path);
                array_splice($re, 1, 0);
                $columnNameArr = [];
                if(empty($re) || count($re)<=0){
                    $json['msg'] = '文件不存在任何数据';
                    echo json_encode($json);
                    exit;
                }
                foreach($re[0] as $item){
                    if(!empty($item) && $item !== ''){
                        $columnNameArr[] = $item;    
                    }
                }
                if(empty($columnNameArr) || count($columnNameArr)<=0){
                    $json['msg'] = '文件不存在任何数据';
                    echo json_encode($json);
                    exit;
                }

                /*将数组的键改为自定义名称*/
                $list = [];
                unset($re[0]);
                $ind = 2;
                foreach($re as $row){
                    $item = [];
                    for($i = 0;$i < count($columnNameArr);$i++){
                        $key = $columnNameArr[$i];
                        $value = $this->TableColumnNameArr[$key];
                        $item_id = 0;
                        if($value == 'mode_id'){
                            $enum_item = searchArray($modes,'name',$row[$i]);
                            $item[$value] = $enum_item['id'];
                            continue;
                        }
                        if($value == 'customer_id'){
                            $enum_item = searchArray($customers,'real_name',$row[$i]);
                            if($enum_item['id']>0){
                                $item[$value] = $enum_item['id'];
                            }else{
                                $customer = [
                                    'regist_id' => 0,
                                    'user_name' => 'heruicheng',
                                    'short_name' => $row[$i],
                                    'master_name' => $row[$i],
                                    'intention_car_count' => 0,
                                    'creator_id' => session('admin')['id'],
                                    'create_time' =>time()
                                ];
                                if($item[$value] = $ctModel->insert($customer,true,true)){
                                    $customer['user_name'] = $customer['user_name'].str_pad($item[$value], 8, "0", STR_PAD_LEFT);
                                    $ctModel->where(['id'=>$item[$value]])->update(['user_name'=>$customer['user_name']]);
                                    $customers = $ctModel->where(['id'=>['>','0']])->select();
                                }
                            }
                            continue;
                        }
                        if($value == 'store_id'){
                            $enum_item = searchArray($stores,'name',$row[$i]);
                            if($enum_item['id']>0){
                                $item[$value] = $enum_item['id'];
                            }else{
                                $store = [
                                    'name' =>  $row[$i],
                                    'store_no' =>  $row[$i],
                                    'creator_id' => session('admin')['id'],
                                    'create_time' =>time()
                                ];
                                if($item[$value] = $stModel->insert($store,true,true)){
                                    $stores = $stModel->where(['id'=>['>','0']])->select();
                                }
                            }
                            continue;
                        }
                        if($value == 'service_id'){
                            $enum_item = searchArray($services,'name',$row[$i]);
                            if($enum_item['id']>0){
                                $item[$value] = $enum_item['id'];
                            }else{
                                $service = [
                                    'mode_name' =>  '业务',
                                    'name' =>  $row[$i],
                                    'sort_id' =>  0,
                                    'score' =>  0,
                                    'remark' =>  $row[$i],
                                    'creator_id' => session('admin')['id'],
                                    'create_time' =>time()
                                ];
                                if($item[$value] = $ceModel->insert($service,true,true)){
                                    $services = $ceModel->where(['id'=>['>','0']])->select();
                                }
                            }
                            continue;
                        }
                        if($value == 'hire_mode'){
                            $enum_item = searchArray($hire_modes,'config_name',$row[$i]);
                            $item[$value] = $enum_item['id'];
                            continue;
                        }
                        if($value == 'car_id'){
                            $item[$value] = 0;
                            if(!empty($cars) && count($cars)>0){
                                $car_list = explode(',',$row[$i]);
                                if(!empty($car_list) && count($car_list)>0){
                                    $car_ids = [];
                                    foreach($car_list as $node){
										$car = searchArray($cars,'plate_no',$node);
                                        $car_ids[] = $car['id'];
                                    }
                                    $item[$value] = $car_ids;
                                    continue;
                                }
                            }
                            continue;
                        }
                        if($value == 'start_time'){
                            $item[$value] = excelTime($row[$i]);
                            continue;
                        }
                        if($value == 'end_time'){
                            $item[$value] = excelTime($row[$i]);
                            continue;
                        }
                        $item[$value] = $row[$i];
                    }
                    $item['cert_files'] = [];
                    if(!empty($imgs) && count($imgs)>0){
                        $cert_files = [];
                        foreach($imgs as $key=>$val){
                            if($key == 'K,'.$ind){
                                $cert_url = $imgs['K,'.$ind];
                                $cert_files[] = $cert_url;
                            }
                        }
                        $item['cert_files'] = $cert_files;
                    }
                    $item['creator_id'] = session('admin')['id'];
                    $item['create_time'] = time();
                    $item['updator_id'] = session('admin')['id'];
                    $item['update_time'] = time();
                    $list[] = $item;
                    $ind++;
                }
                if(empty($list) || count($list)<=0){
                    $json['msg'] = '文件不存在任何数据';
                    echo json_encode($json);
                    exit;
                }
                $count = 0;
                $has_count = 0;
                foreach($list as $item){
                    $data = $item;
                    $this->model = model('Contract');
                    $info = $this->model->where(['contract_no'=>$data['contract_no']])->find();
                    $data['start_time'] = strtotime($data['start_time']);
                    $data['end_time'] = strtotime($data['end_time']);
                    unset($data['cert_files']);
                    $data['data_count'] = count($item['cert_files']);
                    $data['car_id'] = 0;
                    $car_ids = $item['car_id'];
                    $data['businesses_id'] = $this->businesses_id;
                    if(empty($info)){
                        if($id = $this->model->insert($data,true,true)){
                            //保存车辆信息
                            $this->saveContractCar($id,0,$car_ids,[]);
                            //保存合同资料
                            $this->saveContractFile($id,$item['cert_files'],[]);
                            admin_log("新增合同信息，ID：".$id);
                            $count++;
                        }
                    }else{
                        if($this->model->where(['id'=>$info['id']])->update($data)){
                            $id = $info['id'];
                            $contractFileArr = array();
                            $contractFileList = db('ContractFile')->where(['contract_id'=>$info['id']])->select();
                            foreach($contractFileList as $fitem){
                                $contractFileArr[] = $fitem['file_url'];
                            }
                            $contractCarArr = array();
                            $contractCarList = db('ContractCar')->where(['contract_id'=>$info['id']])->select();
                            foreach($contractCarList as $citem){
                                $contractCarArr[] = $citem['car_id'];
                            }
                            //保存车辆信息
                            $this->saveContractCar($info['id'],0,$car_ids,$contractCarArr);
                            //保存合同资料
                            $this->saveContractFile($info['id'],$item['cert_files'],$contractFileArr);
                            admin_log("更新合同信息，ID：".$id);
                            $has_count++;
                        }
                    }
                }
                $json['status'] = $count>0?1:0;
                $json['msg'] = '上传'.($count>0?'成功':'失败').',成功记录 '.$count.' 条,已存在记录 '.$has_count.' 条';
                echo json_encode($json);
                exit;
            }
        }

        echo json_encode($json);
        exit;
    }

    /*
    * 批量删除
    */
    public function betch_del(){
        $json = [
            'status' => 0,
            'msg' => '请选择所要删除的记录'
        ];
        $row_ids = input('row_ids');
        if(!empty($row_ids) && count($row_ids)>0){
            $rowIdArr = explode(',',$row_ids);
            if($this->model->where(['id'=>['in',$rowIdArr]])->delete()){
                db('ContractCar')->where(['contract_id'=>['in',$rowIdArr]])->delete();
                db('ContractCert')->where(['contract_id'=>['in',$rowIdArr]])->delete();
                $json['status'] = 1;
                $json['msg'] = '删除成功';
                admin_log("删除合同，ID：$row_ids");
            }else{
                $json['msg'] = $this->model->getError();
            }
        }

        echo json_encode($json);
        exit;
    }
}